package com.atguigu.paymentdemo.uitl.Distributed;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisDistributedLock {
    @Resource
    private Jedis jedis;

    private final String SUCCESSFLAG = "OK";

    private long waitLockTime = 5000;

    public boolean lock(String orderNo){
        //获取锁超时截至时间，超时不在重复获取锁
        long waitEnd = System.currentTimeMillis() + waitLockTime;
        String result;
        while(System.currentTimeMillis() < waitEnd){
            result = jedis.set(orderNo,orderNo,"NX","PX",50000);
            if(result.equals(SUCCESSFLAG)) return true;
        }
        return false;

    }

    public boolean unlock(String orderNo){
        //解锁
        long result = jedis.del(orderNo);
        return result == 1L;
    }

}
